package cn.edu.fzu.delivery.session;

import static cn.edu.fzu.delivery.session.SessionConstant.SESSION_TIMEOUT;
import static java.util.concurrent.TimeUnit.SECONDS;

import javax.servlet.ServletContext;

import cn.edu.fzu.delivery.common.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Component
public class SessionCache {

    private final LoadingCache<String, RedisSession> cache;

    @Autowired
    public SessionCache(@Qualifier("redisClient") final RedisClient redisClient,
                        @Qualifier("webApplicationContext") final WebApplicationContext webApplicationContext) {

        final ServletContext servletContext = webApplicationContext.getServletContext();
        CacheLoader<String, RedisSession> loader = new CacheLoader<String, RedisSession>() {
            @Override
            public RedisSession load(String key) throws Exception {
                return new RedisSession(redisClient, servletContext, key);
            }
        };

        cache = CacheBuilder.newBuilder().expireAfterAccess(SESSION_TIMEOUT, SECONDS).build(loader);
    }


    RedisSession get(String dSessionId) {
        return cache.getUnchecked(dSessionId);
    }


    void invalidate(String dSessionId) {
        cache.invalidate(dSessionId);
    }
}
